import logging
import os
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import login_required
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.api import users
from django.utils import simplejson

from models import *

from rpc import RPCHandler


class MainPage(webapp.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/html'
        username = users.get_current_user()
        if username:
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'

            profiles = Profile.all()
            profiles.filter("user =", username)
            profile = profiles.get()

            logging.debug(profile)
            if not profile:
                return self.redirect('/createprofile')
            else:
                if not profile.nickname:
                    return self.redirect('/createprofile')

        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Login'

        movies = db.GqlQuery("SELECT * FROM Movie order by average desc LIMIT 100")

        template_values = {
            'movies': movies,
            'url': url,
            'username' : username,
            'url_linktext': url_linktext,
            }

        path = os.path.join(os.path.dirname(__file__),'templates','index.html')
        self.response.out.write(template.render(path, template_values))

class CreateProfile(webapp.RequestHandler):
    @login_required
    def get(self):
        self.response.headers['Content-Type'] = 'text/html'
        username = users.get_current_user()
        url = users.create_logout_url(self.request.uri)
        url_linktext = 'Logout'

        profile = Profile.all().filter("user =", username).get()

        if profile and profile.nickname:
            self.redirect('/profile/%s' % profile.nickname)
        else:
            profile = Profile(abuseflags=0, privacy="everyone")
            profile.put()

        template_values = {
            'profile': profile,
            'url': url,
            'username' : username,
            'url_linktext': url_linktext,
            }

        path = os.path.join(os.path.dirname(__file__),'templates','createprofile.html')
        return self.response.out.write(template.render(path, template_values))


class ViewProfile(webapp.RequestHandler):
    def post(self):
        username = users.get_current_user()
        nickname = self.request.get('nickname')
        profile = Profile.all().filter("user =", username).get()
        if not profile.nickname:
            taken = Profile.all().filter("nickname =", nickname).get()
            if not taken:
                profile.nickname = nickname
        profile.privacy = self.request.get('privacy')
        profile.put()
        return self.redirect('/profile/%s' % profile.nickname)

    def get(self, nickname=None):
        self.response.headers['Content-Type'] = 'text/html'
        username = users.get_current_user()
        myprofile = Profile.all().filter("user =", username).get()
        profile = None
        if username:
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
            if not nickname: # /profile redirect
                if myprofile.properties().has_key('nickname'): # profile must have a nickname to do the redirect
                    return self.redirect('/profile/%s' % myprofile.nickname)
                else:
                    return self.redirect('/createprofile')
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Login'

        profile = Profile.all().filter("nickname =", nickname).get()

        if not profile:
            return self.redirect('/')

        template_values = {
            'profile': profile,
            'myprofile': myprofile,
            'url': url,
            'username' : username,
            'url_linktext': url_linktext,
            }

        path = os.path.join(os.path.dirname(__file__),'templates','profile.html')
        self.response.out.write(template.render(path, template_values))

class ViewFBProfile(webapp.RequestHandler):
    def get(self, nickname=None):
        self.response.headers['Content-Type'] = 'text/html'
        username = users.get_current_user()
        profile = Profile.all().filter("nickname =", nickname).get()

        if not profile:
            return self.redirect('/')

        template_values = {
            'profile': profile,
            }

        path = os.path.join(os.path.dirname(__file__),'templates','fbprofile.html')
        self.response.out.write(template.render(path, template_values))

class AverageRatings(webapp.RequestHandler):
    def get(self): return self.redirect("/")
    def post(self):
        movie = db.get(self.request.get('movie'))
        logging.debug(self.request.get('movie'))
        logging.debug(movie)

        ratings = Rating.all().filter("movie =", movie)
        rsum = 0
        count = 0
        for r in ratings:
            count += 1
            rsum += r.rating

        # update the movie with the new average and number of votes
        movie.rating = rsum
        movie.votes = count
        movie.average = db.Rating(int(rsum / count))
        movie.put()

application = webapp.WSGIApplication(
                                     [('/', MainPage),
                                     (r'/profile/(.*)', ViewProfile),
                                     ('/profile', ViewProfile),
                                     (r'/fb/(.*)', ViewFBProfile),
                                     ('/fb', ViewProfile),
                                     ('/createprofile', CreateProfile),
                                     ('/averageratings', AverageRatings),
                                     ('/rpc', RPCHandler)],
                                     debug=True)


def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
